package mail.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;

/**
 * @author hanjiafeng
 * @Date: 2019-1-10 16:55:29
 * @desc: 调用JS引擎
 */
public class JsInvoker {

    private ScriptEngine nashorn;

    public JsInvoker(String... filePaths) {
        // 获取脚本引擎
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        nashorn = scriptEngineManager.getEngineByName("javascript");
        for (String filePath : filePaths) {
            FileReader fileReader = null;
            try {
                fileReader = new FileReader(filePath);
                nashorn.eval(fileReader);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    Objects.requireNonNull(fileReader).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 加载js方法
     *
     * @param method    需调用的方法
     * @param filePaths 多个js文件路径
     * @return 返回
     */
    @Deprecated
    public static String invokeJs(String method, String... filePaths) {

        // 获取脚本引擎
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        try {

            // 读取js文件内容
            for (String filePath : filePaths) {
                FileReader fileReader = null;
                try {
                    fileReader = new FileReader(filePath);
                    nashorn.eval(fileReader);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Objects.requireNonNull(fileReader).close();
                }
            }

            //调用js代码，进行参数加密
            Object eval = nashorn.eval(method);
            return eval.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "-1";
    }

    public String invokeJs(String method) {

        try {
            //调用js代码，进行参数加密
            Object eval = nashorn.eval(method);
            return eval.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "-1";
    }
}
